package com.neuedu.service.impl;

import com.neuedu.service.MinioService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Service
public class MinioServiceImpl implements MinioService {
    @Resource
    MinioClient minioClient;

    @Override
    public String upload(String bucket, MultipartFile file, Long login_id) throws IOException, ServerException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        StringBuilder builder = new StringBuilder();
        builder.append(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS")));
        Random random = new Random(login_id);
        for (int i = 0; i < 5; i++) {
            builder.append(random.nextInt(0,10));
        }
        builder.append(".").append(FilenameUtils.getExtension(file.getOriginalFilename()));
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucket)
                .contentType(file.getContentType())
                .object(builder.toString())
                .stream(file.getInputStream(), file.getSize(), 0)
                .build();
        minioClient.putObject(args);
        return String.format("/%s/%s", bucket, builder);
    }
}
